import re
import string
import time

from faker import Faker

from utils.fake.areamap import area,areaMap

# /**根据身份证算出地址****/

class Address(object):

    xToken = [['自治区','省','市'],
              ['自治州','市','地区','旗','县','区'],
              ['自治县','市','县','旗','区','路','街']]

    def __init__(self,idcard=''):
        if idcard=='': return

        self.idcard = idcard
        self.area = areaMap[idcard[:6]]
        self.street = Faker('zh_CN').street_address()\
                      +Faker('zh_CN').numerify('@%0%')\
                      +Faker('zh_CN').random_element(['号','＃','房'])

        # self._jieba(self.area+self.street)
        self.parserAddr(self.area+self.street)
        # self.parser_re(self.area+self.street)

    def _jieba(self,str):
        import jieba
        self.xlist=list(jieba.cut(str))
        print(self.xlist)
        return self.xlist

    def parser_re(self,str):
        self.xlist = re_parser(str)

        return self.xlist

    def parserAddr(self,str):

        sindex=0  #游标

        self.xlist=[]

        for token in self.xToken:
            for x in token:  # 省、市、区
                xindex = sindex + str[sindex:].find(x)
                if xindex>sindex:
                    lastindex = xindex+len(x)
                    self.xlist.append(str[sindex:lastindex])
                    sindex = lastindex
                    break
            # str = str[lastindex:]
        self.xlist.append(str[sindex:])

        print(self.xlist)
        return self.xlist


    # /**获取省***/
    def get_shenfen(self,id=''):
        if id=='' : return area[self.idcard[:2]]

        # //截取前两位数
        index = id[:2]
        return area[index]

    def get_city(self,id=''):
        if id =='':
            return self.xlist[1]

        self.area = areaMap[id[:6]]

        ll = self._jieba(self.area)


        return ll[1]

    def get_county(self,id = ''):
        if len(self.xlist)>2 :
            return self.xlist[2]
        else:
            return self.street

    # /**获取地址**/
    def get_addr(self,id=''):
        if id=='':
            return self.area + self.street

        return self.get_area(id)



    def get_area(self,id):

        try:
            index = id[:6]

            return areaMap[index]+Faker('zh_CN').street_address()
        except:
            return ''


# /**
# * @description 根据身份证号码获取出身地址
# * （请根据自己需求就行相应修改  下方提供地区类库）
# * @author Angus
# * @time 2018-07-03
# * @email zhn6@sina.cn
# * @param string $idcard  身份证号码
# * @return string $address
# */
def get_addressByIdcard(idcard, type=1):
    if idcard=='': return ''

    if type == 1:
        # 截取前六位数(获取基体到县区的地址)
        # key = idcard[:6]
        addr = Address().get_addr(idcard)
        if addr!='': return addr

        # 截取前两位数(没有基体到县区的地址就获取省份)
        # key = idcard[:2]
        addr = Address().get_shenfen(idcard)
        if addr!='': return addr

        # 都没有
        return '未知地址'

    elif type == 2:
        # 截取前两位数(只获取省份)
        return Address().get_shenfen(idcard)
    else:
        return None


PATTERN = u'([\u4e00-\u9fa5]{2,5}?(?:省|自治区|市))([\u4e00-\u9fa5]{2,9}?(?:市|旗|县|州|区)){0,1}([\u4e00-\u9fa5]{1,7}?(?:市|旗|区|县|路|街)){0,1}(.+){0,1}'
pattern = re.compile(PATTERN)

def re_parser(str):
    # str =str.decode('utf8')
    province = ''
    city = ''
    district = ''
    other =''

    m = pattern.search(str)
    if not m:
        return 'err:'+str

    retlist=[]
    if m.lastindex >= 1:
        province = m.group(1)
        retlist.append(province)
    if m.lastindex >= 2:
        city = m.group(2)
        if city:retlist.append(city)
    if m.lastindex >= 3:
        district = m.group(3)
        if district:retlist.append(district)
    if m.lastindex >=4:
        other = m.group(4)
        if other:
            retlist.append(other)
        else:
            retlist.append('临时')

    print('%s|%s|%s|%s' % ( province, city, district,other))
    return retlist

def xRe():

    xToken = [['自治区','省','市'],
              ['自治州','市','地区','旗','县','区'],
              ['自治县','市','县','旗','区','路','街']]

    PATTERN = u'([\u4e00-\u9fa5]{2,5}?(?:省|自治区|市))([\u4e00-\u9fa5]{2,9}?(?:市|旗|县|州|区)){0,1}([\u4e00-\u9fa5]{2,7}?(?:市|旗|区|县|路|街)){0,1}'

    # reload(sys)
    # sys.setdefaultencoding('utf8')

    # 匹配规则必须含有u,可以没有r
    # 这里第一个分组的问号是懒惰匹配,必须这么做
    # 注意在linux下PATTERN = ur're'
    PATTERN0 = u'([\u4e00-\u9fa5]{2,5}?(?:省|自治区|市))([\u4e00-\u9fa5]{2,7}?(?:市|区|县|州)){0,1}([\u4e00-\u9fa5]{2,7}?(?:市|区|县)){0,1}'
    PATTERN1 = r'([\u4e00-\u9fa5]{2,5}?(?:省|自治区|市)){0,1}([\u4e00-\u9fa5]{2,7}?(?:市|区|县|州)){0,1}([\u4e00-\u9fa5]{2,7}?(?:村|镇|街道)){1}'
    data_list = ['北京市南瓜村', '陕西省西安市雁塔区大村', '西班牙镇街道', '北京市海淀区', '黑龙江省佳木斯市汤原县大村', '内蒙古自治区赤峰市',
                 '贵州省黔南州贵定县', '新疆维吾尔自治区伊犁州奎屯市','黑龙江省齐齐哈尔市龙沙区蔡街b座302号','云南省西双版纳傣族自治州勐腊县阜新路l座909号']
    pattern = re.compile(PATTERN)

    for data in data_list:
        # data_utf8 = data.decode('utf8')
        data_utf8 = data
        print(data_utf8)

        # province = ''
        # city = ''
        # district = ''
        # # pattern = re.compile(PATTERN3)
        # m = pattern.search(data_utf8)
        # if not m:
        #     print(data + '|||')
        #     continue
        # # print m.group()
        # if m.lastindex >= 1:
        #     province = m.group(1)
        # if m.lastindex >= 2:
        #     city = m.group(2)
        # if m.lastindex >= 3:
        #     district = m.group(3)
        # out = '%s|%s|%s' % ( province, city, district)

        out = re_parser(data_utf8)
        print(out)
    # pattern = re.compile(r'([a-z]+) ([a-z]+)', re.I)



if __name__ == "__main__":
    # xx = Address()
    # print(xx.get_addr(Faker('zh_CN').ssn()) +'--'+ Faker('zh_CN').street_address())
    #
    # print(get_addressByIdcard(Faker('zh_CN').ssn()) +'--'+ Faker('zh_CN').street_address())
    #
    # print(xx.get_city(Faker('zh_CN').ssn()))
    time_start = time.time()
    yy = Address(Faker('zh_CN').ssn())

    print(yy.get_addr())
    print(yy.get_shenfen())
    print(yy.get_city())
    print(yy.get_county())
    print(yy.get_addr())
    print(yy.xlist)

    print('totally cost = ', time.time()-time_start)

    xRe()

    print(re_parser('吉林省长春市彭路w座302号'))
    print(re_parser('广西壮族自治区百色市林路z座9108号'))